package com.xieshue.im.client;

import com.xieshue.im.ChannleManager;
import com.xieshue.im.LocalChannel;
import com.xieshue.im.client.handler.ImClientChannelHandler;
import com.xieshue.im.handler.codec.ImMessageDecoder;
import com.xieshue.im.handler.codec.ImMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IM client 启动类
 *
 * @author xieshue
 * @date 2017\12\12 0012
 */
public class ImClientBootstrap {
    private static final Logger logger = LoggerFactory.getLogger(ImClientBootstrap.class);

    private Bootstrap bootstrap;
    private ConnectConfig connectConfig;

    public ImClientBootstrap(ConnectConfig connectConfig) {
        this.connectConfig = connectConfig;
    }

    public void connect() throws Exception {
        if (logger.isDebugEnabled()) {
            logger.info("连接netty服务...");
        }
        EventLoopGroup worksGroup = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();
            bootstrap.group(worksGroup)
                    .channel(NioSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO));
            ChannelFuture future;
            synchronized (bootstrap) {
                bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("encoder", new ImMessageEncoder());
                        ch.pipeline().addLast("decoder", new ImMessageDecoder());
                        ch.pipeline().addLast(new ImClientChannelHandler());
                    }
                });
                future = bootstrap.connect(connectConfig.getHost(), connectConfig.getPort());
            }
            future.sync();
            if (logger.isDebugEnabled()) {
                logger.info("连接netty服务成功...");
            }
            LocalChannel localChannel = new LocalChannel();
            localChannel.setChannel(future.channel());
            localChannel.setTicket(0);
            ChannleManager manager = ChannleManager.getInstance();
            future.channel().closeFuture().sync();
        } catch (Throwable t) {
            throw new Exception("connects to  fails", t);
        } finally {
            if (logger.isDebugEnabled()) {
                logger.info("与netty服务断开连接...");
            }
//            worksGroup.shutdownGracefully();
        }
    }
}
